﻿using AutoTask.Model;
using AutoTask.Model.DB;
using RpcClient;
using RpcHelper;
using SqlSugarHelper;

namespace AutoTask.DAL.Repository
{
    internal class AutoTaskItemDAL : IAutoTaskItemDAL
    {
        private IRepository<AutoTaskItemModel> _BasicDAL;
        public AutoTaskItemDAL(IRepository<AutoTaskItemModel> dal)
        {
            _BasicDAL = dal;
        }
        public AutoTaskItem[] Gets(Guid taskId)
        {
            return _BasicDAL.Gets(c => c.TaskId == taskId && c.IsEnable, c => new AutoTaskItem
            {
                SendParam = c.SendParam,
                SendType = c.SendType,
                SuccessSetup = c.SuccessSetup,
                FailSetup = c.FailSetup,
                FailNextSetup = c.FailNextSetup,
                ItemSort = c.ItemSort,
                Id = c.Id,
                NextSetup = c.NextSetup,
                LogRange = c.LogRange,
                ItemTitle = c.ItemTitle,
                TimeOut = c.TimeOut,
                RetryNum = c.RetryNum
            });
        }

        public void SyncState(SyncItemResult[] datas)
        {
            DateTime now = DateTime.Now;
            AutoTaskItemModel[] models = datas.ConvertAll(c => new AutoTaskItemModel { 
                Id=c.ItemId,
                ErrorCode=c.ErrorCode,
                IsSuccess=c.IsSuccess,
                LastExecTime=now
            });
            if (!this._BasicDAL.UpdateOnly(models, c => new { 
                c.IsSuccess,
                c.ErrorCode,
                c.LastExecTime
            }))
            {
                throw new ErrorException("task.item.sync.fail");
            }
        }
    }
}
